import java.util.Deque;
import java.util.LinkedList;

import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=226 lang=java
 *
 * [226] 翻转二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        //采用层次遍历,其他遍历也可
        if(root==null) return root;
        Deque<TreeNode> que=new LinkedList<>();
        que.offer(root);
        while(!que.isEmpty()){
            TreeNode front=que.poll();
            if(front.left!=null){
                que.offer(front.left);
            }
            if(front.right!=null){
                que.offer(front.right);
            }
            TreeNode temp=front.left;
            front.left=front.right;
            front.right=temp;
        }
        return root;

        //递归法
        // if(root==null) return null;
        //翻转右子树给左子树，翻转左子树给右子树
        // TreeNode left=invertTree(root.left);
        // TreeNode right=invertTree(root.right);
        // root.left=right;
        // root.right=left;
        // return root;
    }
}
// @lc code=end

